package com.briup.emdc.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author Kevin
 * @since 2024.04.09
 **/
public class DBUtils{
    private static Properties prop;

    static{
        try{
            InputStream is=ClassLoader.getSystemResourceAsStream("db.properties");
            prop=new Properties();
            prop.load(is);
            Class.forName(prop.getProperty("driver-class"));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private DBUtils(){}

    public static Connection getConn() throws Exception{
        String url=prop.getProperty("url");
        String user=prop.getProperty("user");
        String password=prop.getProperty("password");

        return DriverManager.getConnection(url,user,password);
    }

    public static void close(ResultSet rs,Statement st,Connection conn){
        if(rs!=null){
            try{
                rs.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        if(st!=null){
            try{
                st.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }

    public static int batchSize(){
        return Integer.parseInt(prop.getProperty("batch-size"));
    }

    public static boolean tableExists(Connection conn,String db,String tableName) throws Exception{
        Statement st=conn.createStatement();
        ResultSet rs=st.executeQuery("show tables from "+db);
        boolean exists=false;
        while(rs.next()){
            String tName=rs.getString(1);
            if(tableName.equals(tName)){
                exists=true;
                break;
            }
        }
        return exists;
    }
}
